<?php

use app\model\Model;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT;
use Firebase\JWT\Key as JwtKey;
use Firebase\JWT\SignatureInvalidException;

// 应用公共文件
/**
 * 用于构建模型搜索器参数
 * 去掉数组空字符串,返回所有键
 *
 * @param array $keys
 * @param array $where
 */
function where_filter(&$keys, array $where)
{
    // 去掉数组里的空字符串和null
    $where = array_filter($where, function ($k) {
        return ($k === '' || $k === null) ? false : true;
    });
    // 拿到所有键
    $keys = array_keys($where);
    // 返回数组
    return $where;
}

function success($data=[], $msg="ok", $code=0)
{
    $info = [
        'code'  => $code,
        'msg'   => $msg,
        'data'  => $data
    ];
    if(is_null($data)){
        unset($info['data']);
    }
    return json($info);
}

function pageSuccess($count=0, $data=[], $msg="ok", $code=0)
{
    return json([
        'code'  => $code,
        'msg'   => $msg,
        'count' => $count,
        'data'  => $data
    ]);
}

function error($msg='', $code=-1)
{
    return json([
        'code' => $code,
        'msg' => $msg,
    ]);
}


/**
 * 实例化Model
 * @param string $table Model名称
 * @return Model
 */
function model($table = '')
{
    return new Model($table);
}

function checkRequest($type)
{
    if (strtolower(request()->method()) !== strtolower($type)) {
        throw new Exception('请求方式错误!');
    }
}

function signPassword(string $password)
{
    return '$2y$10$cVPJshI2WOHlR6dz4LgjieVTl7bfPCDq8Yeie2wz698D0IKiXkrUO';
}

function getRequestData(array $fields)
{
    return request()->only($fields, 'param', 'trim');
}

function getConstOption($name)
{
    return config("const.{$name}");
}

/**
 * 生成token
 */
function signToken($uid)
{
    $key = 'app';
    $now = time();
    $payload = [
        'iss' => '', // 签发者，可以空
        'aud' => '', // 面象的用户,可以空
        'iat' => $now, // 签发时间
        'nbf' => $now + 3, // 签发什么时候生效
        'exp' => $now + 3600, // token过期时间
        'data' => [
            'uid' => $uid
        ]
    ];
    return JWT::encode($payload, $key, 'HS256');
}


function checkToken($token)
{
    $key = 'app';
    $result = JWT::decode($token, new JwtKey($key, 'HS256'));
    $user = $result->data;
    return !empty($user->uid);
}

function writeLog($content)
{
    if (is_array($content)) {
        $content = json_encode($content);
    }
    \think\facade\Log::write($content, 'info');
}